/*
 * Copyright (C) 2020 唐家林
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package db

import (
	"database/sql"
)

type InterfaceDao struct {
}

func NewInterfaceDao() *InterfaceDao {
	return &InterfaceDao{}
}

// 获取所有的表信息
func (dao *InterfaceDao) FindAll() ([]Interface, error) {
	rows, err := DB.Query("SELECT * FROM interface")
	defer rows.Close()
	if err != nil {
		return nil, err
	}
	list := make([]Interface, 0)
	for rows.Next() {
		data := Interface{}
		if err := rows.Scan(&data.Id, &data.Name, &data.PrimaryJson, &data.AssistantJson); err != nil {
			return nil, err
		}
		list = append(list, data)
	}
	return list, nil
}

func (dao *InterfaceDao) FindById(id int64) (*Interface, error) {
	data := &Interface{}
	row := DB.QueryRow("SELECT * FROM interface WHERE id = ?", id)
	if err := row.Scan(&data.Id, &data.Name, &data.PrimaryJson, &data.AssistantJson);
		err != nil && err != sql.ErrNoRows {
		return nil, err
	}
	return data, nil
}

// 存储接口信息
func (dao *InterfaceDao) Save(data *Interface) error {
	var r sql.Result
	var err error
	if data.Id == 0 {
		r, err = DB.Exec("INSERT INTO interface (name, primary_json, assistant_json) VALUES (?, ?, ?)",
			data.Name, data.PrimaryJson, data.AssistantJson)
		if err != nil {
			return err
		}
		id, err := r.LastInsertId()
		if err != nil {
			return err
		}
		data.Id = id
	} else {
		r, err = DB.Exec("UPDATE interface set name = ?, primary_json = ?, assistant_json = ? where id = ?",
			data.Name, data.PrimaryJson, data.AssistantJson, data.Id)
		if err != nil {
			return err
		}
		_, err := r.RowsAffected()
		if err != nil {
			return err
		}
	}
	return nil
}

// 删除接口信息
func (dao *InterfaceDao) Delete(id int64) {
	_, _ = DB.Exec("DELETE FROM interface WHERE id = ?", id)
}
